import { ExportFormat, DocData } from './export-types'
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'

// 统一渲染工具：复用预览页面的 markdown-it + highlight.js + .milkdown-preview 样式
export function renderMarkdownToHtml(content: string, isDark: boolean = false, font: string = ''): string {
  const md = new MarkdownIt({
    html: true,
    linkify: true,
    typographer: true,
    breaks: true,
    highlight: function (str, lang) {
      if (lang && hljs.getLanguage(lang)) {
        try {
          return hljs.highlight(str, { language: lang }).value
        } catch (__) {}
      }
      return ''
    }
  })
  // 渲染为 HTML
  let html = md.render(content || '')
  // 包裹 .milkdown-preview 容器
  html = `<div class="milkdown-preview${isDark ? ' dark' : ''}" style="${font ? `font-family:${font};` : ''}">${html}</div>`
  return html
}

// 获取 .milkdown-preview 的全部 CSS（可直接复制 index.css 相关内容，或动态提取）
// 这里直接内联 index.css 里 .milkdown-preview 相关样式
export function getMilkdownPreviewCss(): string {
  return `
/* 页面整体样式 - 添加留白 */
body { 
  margin: 0; 
  padding: 0; 
  background: #ffffff; 
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans", Helvetica, Arial, sans-serif;
}

/* 内容容器 - 模拟预览效果的留白 */
.content-container {
  max-width: 64rem; /* max-w-5xl */
  margin: 0 auto;
  padding: 1.5rem; /* p-6 */
  background: #ffffff;
  min-height: 100vh;
}

/* 深色模式 */
.dark .content-container {
  background: #1f2937;
}

.milkdown-preview { width: 100%; height: 100%; line-height: 1.6; color: #333; }
.milkdown-preview.dark { color: #f3f4f6; background: transparent; }
.milkdown-preview h1, .milkdown-preview h2, .milkdown-preview h3, .milkdown-preview h4, .milkdown-preview h5, .milkdown-preview h6 { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-weight: bold; margin-bottom: 1rem; }
.milkdown-preview h1 { font-size: 2rem; }
.milkdown-preview h2 { font-size: 1.5rem; }
.milkdown-preview h3 { font-size: 1.25rem; }
.milkdown-preview p { margin-bottom: 1rem; line-height: 1.7; }
.milkdown-preview strong { font-weight: bold; }
.milkdown-preview em { font-style: italic !important; font-family: inherit !important; font-weight: 500; }
.milkdown-preview i { font-style: italic !important; font-family: inherit !important; }
.milkdown-preview *[style*="italic"] { font-style: italic !important; }
.milkdown-preview .emphasis { font-style: italic !important; }
.milkdown-preview em, .milkdown-preview i, .milkdown-preview .italic, .milkdown-preview [data-emphasis="true"] { font-style: italic !important; font-family: inherit !important; }
.milkdown-preview pre { background: #1f2937; color: #f3f4f6; overflow-x: auto; padding: 1rem; border-radius: 0.5rem; margin: 1rem 0; border: 1px solid #374151; }
.milkdown-preview pre code { background: transparent; padding: 0; border: none; color: inherit; }
.milkdown-preview hr { border: none; border-top: 2px solid #e5e7eb; margin: 2rem 0; }
.milkdown-preview.dark hr { border-top-color: #4b5563; }
.milkdown-preview a { color: #2563eb; text-decoration: underline; text-decoration-color: #93c5fd; }
.milkdown-preview.dark a { color: #60a5fa; text-decoration-color: #3b82f6; }
.milkdown-preview a:hover { text-decoration-color: currentColor; }
.milkdown-preview img { max-width: 100%; border-radius: 0.5rem; margin: 1rem 0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); }
.milkdown-preview table { border-collapse: collapse; width: 100%; border: 1px solid #e5e7eb; margin: 1rem 0; }
.milkdown-preview.dark table { border-color: #374151; }
.milkdown-preview th { background: #f9fafb; padding: 0.5rem; border: 1px solid #d1d5db; font-weight: 600; }
.milkdown-preview.dark th { background: #374151; border-color: #4b5563; }
.milkdown-preview td { padding: 0.5rem; border: 1px solid #e5e7eb; }
.milkdown-preview.dark td { border-color: #374151; }
.milkdown-preview tr:nth-child(even) { background: #f9fafb; }
.milkdown-preview.dark tr:nth-child(even) { background: #374151; }
.milkdown-preview tr:hover { background: #f3f4f6; }
.milkdown-preview.dark tr:hover { background: #4b5563; }
.milkdown-preview del { text-decoration: line-through; color: #6b7280; }
.milkdown-preview input[type="checkbox"] { margin-right: 0.5rem; }
.milkdown-preview .footnote { font-size: 0.875rem; color: #6b7280; border-top: 1px solid #e5e7eb; margin-top: 2rem; padding-top: 1rem; }
.milkdown-preview.dark .footnote { color: #9ca3af; border-top-color: #4b5563; }
.milkdown-preview br { display: block; margin: 0.5rem 0; }
.milkdown-preview .milkdown .editor .ProseMirror { width: 100%; height: 100%; padding: 0; border: none; outline: none; }
.milkdown-preview .milkdown .editor .ProseMirror > * { margin-bottom: 1rem; }
.milkdown-preview .milkdown .editor .ProseMirror > *:last-child { margin-bottom: 0; }
@media (max-width: 768px) { .milkdown-preview { padding: 1rem; font-size: 14px; } .milkdown-preview h1 { font-size: 2rem; } .milkdown-preview h2 { font-size: 1.5rem; } }
.milkdown-preview .milkdown { width: 100%; height: 100%; }
.milkdown-preview .milkdown .editor { width: 100%; height: 100%; }
`;
}

// Markdown格式处理器（原样导出）
export class MarkdownProcessor {
  process(docs: DocData[], addWatermark: boolean): string {
    let content = ''
    if (docs.length === 1) {
      const doc = docs[0]
      if (addWatermark) {
        content += '> 由 free-doc 生成\n\n'
      }
      content += doc.docContent || ''
    } else {
      if (addWatermark) {
        content += '> 由 free-doc 生成\n\n'
      }
      docs.forEach((doc, idx) => {
        content += `# ${doc.docTitle}\n\n`
        content += doc.docContent || ''
        content += '\n\n---\n\n'
      })
    }
    return content
  }
}

// HTML格式处理器（复用统一渲染工具+内联CSS）
export class HtmlProcessor {
  process(docs: DocData[], addWatermark: boolean, isDark: boolean = false, font: string = ''): string {
    let html = ''
    if (docs.length === 1) {
      html = renderMarkdownToHtml((addWatermark ? '> 由 free-doc 生成\n\n' : '') + (docs[0].docContent || ''), isDark, font)
    } else {
      let all = addWatermark ? '> 由 free-doc 生成\n\n' : ''
      docs.forEach((doc, idx) => {
        all += `# ${doc.docTitle}\n\n`
        all += doc.docContent || ''
        all += '\n\n---\n\n'
      })
      html = renderMarkdownToHtml(all, isDark, font)
    }
    // 内联CSS
    const css = getMilkdownPreviewCss()
    // 将内容包装在content-container中，添加两边留白
    const contentWithMargin = `<div class="content-container${isDark ? ' dark' : ''}">${html}</div>`
    return `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>导出文档</title><style>${css}</style></head><body>${contentWithMargin}</body></html>`
  }
}

// PDF格式处理器（用 html2pdf.js 或 jsPDF）
export class PdfProcessor {
  async process(docs: DocData[], addWatermark: boolean, isDark: boolean = false, font: string = ''): Promise<Blob> {
    // 动态导入 html2pdf.js
    const html2pdf = (await import('html2pdf.js')).default
    const html = new HtmlProcessor().process(docs, addWatermark, isDark, font)
    return new Promise((resolve, reject) => {
      html2pdf()
        .from(html)
        .outputPdf('blob')
        .then((blob: Blob) => resolve(blob))
        .catch(reject)
    })
  }
}

// 格式处理器工厂
export class FormatProcessorFactory {
  static create(format: ExportFormat) {
    switch (format) {
      case ExportFormat.MARKDOWN:
        return new MarkdownProcessor()
      case ExportFormat.HTML:
        return new HtmlProcessor()
      case ExportFormat.PDF:
        return new PdfProcessor()
      default:
        return new MarkdownProcessor()
    }
  }
} 